<template>
  <div class="p16">
    <van-cell-group inset>
      <van-cell title="统计" />
      <van-cell title="最近天数">
        <template #right-icon>
          <van-stepper v-model="days" min="7" integer />
        </template>
      </van-cell>
      <div style="margin: 12px 16px 0 16px">
        <van-button round block type="primary" @click="load">刷新</van-button>
      </div>
    </van-cell-group>
    <van-cell-group inset style="margin-top: 16px">
      <van-cell v-for="(v,i) in series" :key="i" :title="getDateLabel(i)" :value="String(v)" />
    </van-cell-group>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useChildrenStore } from '@/stores/children'
import dayjs from 'dayjs'
import timezone from 'dayjs/plugin/timezone'
import utc from 'dayjs/plugin/utc'

dayjs.extend(utc)
dayjs.extend(timezone)

const children = useChildrenStore()
const days = ref(14)
const series = ref<number[]>([])
const startDate = ref<string>('')

onMounted(async () => {
  await children.load()
  await load()
})

async function load() {
  if (!children.currentChildId) return
  const res = await $fetch('/api/summary/timeline', { params: { childId: children.currentChildId, days: String(days.value) } })
  series.value = res.series
  startDate.value = res.start
}

// 根据索引获取日期标签
function getDateLabel(index: number): string {
  if (!startDate.value) return `第 ${index + 1} 天`

  const date = dayjs(startDate.value).add(index, 'day')
  return date.format('MM月DD日')
}
</script>


